﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JyFramework
{
    public class BasePoolObject
    {
        protected object[] _args;
        public BasePoolObject()
        {

        }

        public BasePoolObject(params object[] args)
        {
            _args = args;
        }

        public virtual void InitSelf(params object[] args)
        {
            _args = args;
        }

        public virtual void CleanSelf()
        {
            _args = null;
        }
    }

    public class ObjectPool<T> where T : BasePoolObject
    {
        protected Stack<T> _unUsePoolObjs;
        protected List<T> _usedPoolObjs;

        protected int _capacity;

        public ObjectPool(int capacity)
        {
            _capacity = capacity;
            _unUsePoolObjs = new Stack<T>();
            _usedPoolObjs = new List<T>();

            for(int i = 0; i < _capacity; i++)
            {
                _unUsePoolObjs.Push(default(T));
            }
        }

        public ObjectPool()
        {
        }

        public T GetObject(params object[] args)
        {
            if(_unUsePoolObjs.Count <= 0)
            {
                _unUsePoolObjs.Push(default(T));
            }

            T value = _unUsePoolObjs.Pop();
            value.InitSelf(args);

            _usedPoolObjs.Add(value);

            return value;
        }

        public void ReleaseObject(T obj)
        {
            obj.CleanSelf();
            if(_usedPoolObjs.Contains(obj))
            {
                _usedPoolObjs.Remove(obj);
            }

            if (_unUsePoolObjs.Count < _capacity)
            {
                _unUsePoolObjs.Push(obj);
            }
            else
            {
                obj = null;
            }
        }


    }
}
